<template>
  <div style="margin: 50px">
    <el-card class="box-card" style="margin: 20px;background-color: white">
      <div slot="header" class="clearfix" align="center">
        <span>更改密码</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="15%">
        <el-form-item label="用户名">
          <el-input v-model="form.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="form.roles" disabled></el-input>
        </el-form-item>
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="form.oldPassword" placeholder="请输入旧密码" type="password"  show-password/>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="form.newPassword" placeholder="请输入新密码" type="password"  show-password/>
        </el-form-item>
        <el-form-item label="新密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" placeholder="再输入新密码" type="password"  show-password/>
        </el-form-item>
      </el-form>
      <el-button style="float: right;margin: 20px" @click="r">取消</el-button>
      <el-button type="primary" style="float: right;margin: 20px" @click="submit">保存</el-button>
    </el-card>
  </div>
</template>

<script>
import { getInfo, updatePwd } from '@/api/user'
export default {
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.form.newPassword !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      form: {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined
      },
      // 表单校验
      rules: {
        oldPassword: [
          {required: true, message: "旧密码不能为空", trigger: "blur"}
        ],
        newPassword: [
          {required: true, message: "新密码不能为空", trigger: "blur"},
          {min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur"}
        ],
        confirmPassword: [
          {required: true, message: "确认密码不能为空", trigger: "blur"},
          {required: true, validator: equalToPassword, trigger: "blur"}
        ]
      },
    }
  },
  mounted() {
    getInfo().then(res => {
      this.form = res.data
    })
  },
  methods: {
    submit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updatePwd(this.form.oldPassword, this.form.newPassword).then(response => {
            this.$message.success("修改成功");
            this.$router.push('/');
          });
        }
      });
    },
    r(){
      this.$router.push('/');
    }
  }
}
</script>

<style>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.box-card {
  width: 480px;
}
</style>
